import router from '@/router'
import store from '@/store'
import getPageTitle from './utils/get-page-title'

const whiteList = ['/login', '/404']
router.beforeEach(async(to, form, next) => {
  const token = store.state.user.token
  if (token) {
    await store.dispatch('user/getUserInfo')
    // 如果有 token 还要去登录页 则打回还是去主页
    if (to.path === '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

// 动态标题设置
router.beforeEach((to, from, next) => {
  document.title = getPageTitle(to.meta.title)
  next()
})
